<!--  批量修改人力统计数据 -->
<template>
  <el-dialog v-model="dialogFormVisible" title="批量编辑员工" width="300px" destroy-on-close draggable>
    <div style="text-align: left" v-if="false">
      <el-card v-for="(item1, idx1) in groupedData" :key="idx1">
        <template #header>{{ item1.name }}</template>
        <div v-for="(item2, idx2) in item1.child" :key="idx2">
          <div>{{ item2.name }}</div>
          <div style="display: flex">
            <el-space wrap>
              <el-card v-for="(item3, idx3) in item2.child" :key="idx3">
                <template #header>{{ item3.name }}</template>
                <div v-for="(item4, idx4) in item3.child" :key="idx4">
                  {{ item4.columnName }}
                </div>
              </el-card>
            </el-space>
          </div>
        </div>
      </el-card>
    </div>
    <el-form ref="ruleFormRef" :model="form" :rules="rules">
      <el-form-item label="人数" prop="userNum">
        <el-input-number v-model="form.userNum" :min="1" :max="99999" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handlerClickBtnSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { FormRules } from 'element-plus'
import http from '../../http'
import { ElMessage, ElLoading } from 'element-plus'

const emits = defineEmits(['submited'])

const ruleFormRef = ref()
const dialogFormVisible = ref(false)

const groupedData = ref<any[]>([])
const editColumnsIds = ref<any[]>([])
const form = reactive({
  userNum: 0,
})

const rules = reactive<FormRules>({
  userNum: [
    {
      required: true,
      validator: (rule: any, value: number, callback: any) => {
        if (rule) {
        }
        if (value < 0) {
          callback(new Error('人数必须大于 0'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

const openDialog = (editColumns: any[]) => {
  dialogFormVisible.value = true

  editColumnsIds.value = editColumns.map((item) => item.id)

  console.log('editColumnsIds', editColumnsIds)

  // 三层分组结果（数组格式）
  const groupedResult: any[] = []

  // 临时存储分组映射关系
  const projectMap = new Map()

  editColumns.forEach((item) => {
    // 第一层：projectName
    let projectGroup = projectMap.get(item.projectName)
    if (!projectGroup) {
      projectGroup = {
        name: item.projectName,
        child: [],
        _map: new Map(), // 用于第二层查找
      }
      projectMap.set(item.projectName, projectGroup)
      groupedResult.push(projectGroup)
    }

    // 第二层：parentDeptName
    let parentDeptGroup = projectGroup._map.get(item.parentDeptName)
    if (!parentDeptGroup) {
      parentDeptGroup = {
        name: item.parentDeptName,
        child: [],
        _map: new Map(), // 用于第三层查找
      }
      projectGroup._map.set(item.parentDeptName, parentDeptGroup)
      projectGroup.child.push(parentDeptGroup)
    }

    // 第三层：deptName
    let deptGroup = parentDeptGroup._map.get(item.deptName)
    if (!deptGroup) {
      deptGroup = {
        name: item.deptName,
        child: [],
      }
      parentDeptGroup._map.set(item.deptName, deptGroup)
      parentDeptGroup.child.push(deptGroup)
    }

    // 添加当前项到对应分组
    deptGroup.child.push(item)
  })

  groupedData.value = groupedResult
}

const handlerClickBtnSubmit = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      const res: any = []
      editColumnsIds.value.forEach((id) => {
        res.push(
          http({
            method: 'PUT',
            path: '/dev-api/oa/requirement',
            params: {
              id,
              weekUserNum: form.userNum,
            },
          })
        )
      })
      const requesets = await Promise.all(res)
      const result = requesets.reduce(
        (acc: any, obj: any) => {
          if (obj.code === 200) {
            acc.count200++
          }
          if (obj.code === 500) {
            acc.count500++
          }
          return acc
        },
        { count200: 0, count500: 0 }
      )
      loading.close()
      if (editColumnsIds.value.length === result.count200) {
        ElMessage({
          message: `修改成功！`,
          grouping: true,
          type: 'success',
        })
        dialogFormVisible.value = false
        emits('submited')
      } else {
        ElMessage({
          message: `修改失败！`,
          grouping: true,
          type: 'error',
        })
      }
    }
  })
}

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped></style>
